﻿using NLog;
using SqlSugar;

namespace LvcChong.DB
{
    public class ConnectionConfigUtil
    {
        private static ILogger _logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 生成数据库客户端配置
        /// </summary>
        /// <param name="configId"></param>
        /// <param name="connectionStr"></param>
        /// <param name="dbType"></param>
        /// <returns></returns>
        public static ConnectionConfig CreateConnection(dynamic configId, string connectionStr, DbType dbType, string schema = "", AopEvents aopEvents = null)
        {
            return new ConnectionConfig
            {
                ConfigId = configId,
                ConnectionString = DESHelper.DesDecrypt(connectionStr),// connectionStr,
                DbType = dbType,
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true,
                MoreSettings = new ConnMoreSettings
                {
                    DisableNvarchar = true,
                    PgSqlIsAutoToLower = false, // 增删查改支持驼峰表
                    PgSqlIsAutoToLowerCodeFirst = false, // 建表建驼峰表。5.1.3.30-preview05
                },
                AopEvents = aopEvents ?? new AopEvents
                {
                    DataExecuting = (oldValue, entityInfo) =>
                    {
                        ////inset生效
                        //if (entityInfo.PropertyName == "CreateTime" && entityInfo.OperationType == DataFilterType.InsertByObject)
                        //{
                        //    entityInfo.SetValue(DateTime.Now);//修改CreateTime字段
                        //                                      //entityInfo有字段所有参数
                        //}
                        ////update生效
                        //if (entityInfo.PropertyName == "UpdateTime" && entityInfo.OperationType == DataFilterType.UpdateByObject)
                        //{
                        //    entityInfo.SetValue(DateTime.Now);//修改UpdateTime字段
                        //}

                        //根据当前列修改另一列 可以么写
                        //if(当前列逻辑==XXX)
                        //var properyDate = entityInfo.EntityValue.GetType().GetProperty("Date");
                        //if(properyDate!=null)
                        //properyDate.SetValue(entityInfo.EntityValue,1);
                    },
                    OnDiffLogEvent = diffModel =>
                    {
                        //操作前记录  包含： 字段描述 列名 值 表名 表描述
                        //var editBeforeData = diffModel.BeforeData;//插入Before为null，之前还没进库
                        //                                          //操作后记录   包含： 字段描述 列名 值  表名 表描述
                        //var editAfterData = diffModel.AfterData;
                        //var sql = diffModel.Sql;
                        //var parameter = diffModel.Parameters;
                        //var data = diffModel.BusinessData;//这边会显示你传进来的对象
                        //var time = diffModel.Time;
                        //var diffType = diffModel.DiffType;//enum insert 、update and delete

                        //Write logic
                    },
                    OnError = e =>
                    {
                        //exp.sql 这样可以拿到错误SQL，性能无影响拿到ORM带参数使用的SQL

                        //5.0.8.2 获取无参数化 SQL  对性能有影响，特别大的SQL参数多的，调试使用
                        _logger.Error(UtilMethods.GetSqlString(dbType, e.Sql, (SugarParameter[])e.Parametres));
                    },
                    OnExecutingChangeSql = (sql, parameters) =>
                    {
                        //sql=newsql
                        //foreach(var p in pars) //修改
                        return new KeyValuePair<string, SugarParameter[]>(sql, parameters);
                    },
                    OnLogExecuted = (sql, parameters) =>
                    {
                        //执行完了可以输出SQL执行时间 (OnLogExecutedDelegate)
                        //执行时间超过1秒
                        //if (Client.Ado.SqlExecutionTime.TotalSeconds > 1)
                        //{
                        //    //代码CS文件名
                        //    var fileName = Client.Ado.SqlStackTrace.FirstFileName;
                        //    //代码行数
                        //    var fileLine = Client.Ado.SqlStackTrace.FirstLine;
                        //    //方法名
                        //    var FirstMethodName = Client.Ado.SqlStackTrace.FirstMethodName;
                        //    //db.Ado.SqlStackTrace.MyStackTraceList[1].xxx 获取上层方法的信息
                        //}
                        //相当于EF的 PrintToMiniProfiler
                    },
                    OnLogExecuting = (sql, parameters) =>
                    {
                        //5.0.8.2 获取无参数化 SQL
                        _logger.Trace(UtilMethods.GetSqlString(dbType, sql, parameters));
                    },
                },
                ConfigureExternalServices = new ConfigureExternalServices()
                {
                    EntityNameService = (type, entity) =>
                    {
                        if (!string.IsNullOrWhiteSpace(schema))
                            entity.DbTableName = $"{schema}.{entity.DbTableName}";
                        //修改表
                    },
                    EntityService = (type, column) =>
                    {
                        //修改列
                    }
                }
            };
        }
    }
}